package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContent;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.HomePageResponse;
import com.cskaoyan.shopping.dto.PanelContentItemDto;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.service.IHomeService;
import javafx.scene.layout.Pane;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: IHomeServiceImpl
 * @Description: Homepage实现类
 * @Author:YPS
 * @Date: 2022/5/19 12:25
 * @Version: 1.0
 **/
@Transactional
@Service
public class IHomeServiceImpl implements IHomeService {

    @Autowired
    PanelContentMapper panelContentMapper;
    @Autowired
    PanelMapper panelMapper;
    @Autowired
    ContentConverter contentConverter;
    @Override
        /*
         显示首页商品信息，显示的是Panel信息，但是这里注意下，如何获取Panel信息呢？
         1. 先调用 PanelMapper selectPanelContentById，自己看下sql语句，获取 List<Panel>
         2. Panel对象中，少了 List<PanelContentItem> panelContentItems
         3. 因此，需要遍历List中的Panel，在调用PanelContentMapper 的 selectPanelContentAndProductWithPanelId方法
            获取List<PanelContentItem>，利用MapStruct将其转化为 List<PanelContentItemDto>
         4. 然后set 到Panel

     */
    public HomePageResponse homepage() {
        HomePageResponse response = new HomePageResponse();
        try {
            Set<PanelDto> panelDtos = new HashSet<>();
            List<Panel> panelList = panelMapper.selectAll();

            for (int i = 0; i < panelList.size(); i++) {
                PanelDto panelDto = contentConverter.panel2Dto(panelList.get(i));
                panelDtos.add(panelDto);
            }

            for (PanelDto panelDto : panelDtos) {
                Integer id = panelDto.getId();
                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(id);
                List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);
                panelDto.setPanelContentItems(panelContentItemDtos);
            }
            response.setPanelContentItemDtos(panelDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }
}
